import urllib
import datetime
import os
import re
import string

from django.core.exceptions import ObjectDoesNotExist

from constants import HYPERIUMS_HAPI_ROOT, HYPERIUMS_RANK, X_MIN, X_MAX, Y_MIN, Y_MAX, ADDED_SYSTEMS, REMOVED_SYSTEMS
from player.models import OCBPlayer, Player, Ally
from planet.models import Planet, PlanetInfo, PlanetMessage

def get_message_from_url(url=None):
    print url
    opened_url = urllib.urlopen(url)
    message = opened_url.read()
    return message

def authenticate_from_hapikey(login=None,auth_key=None):
    authentication_url = HYPERIUMS_HAPI_ROOT+"game=Hyperiums7&player="+login+"&hapikey="+auth_key
    message = get_message_from_url(authentication_url)
    login_informations = dict([info.split('=') for info in message.split('&')])
    return login_informations

def _download_file(type=None):
    download_url = HYPERIUMS_HAPI_ROOT+"game=Hyperiums7&player=t1t0u&passwd=moulon91&request=download&filetype="+type
    print download_url 
    opened_url = urllib.urlopen(download_url)
    handler = opened_url.read()
    file_name = type+".txt.gz"
    file = open(file_name,"w")
    file.write(handler)
    file.close()

def download_files():
    _download_file(type="players")
    os.system("gunzip -f players.txt.gz")
    
    _download_file(type="alliances")
    os.system("gunzip -f alliances.txt.gz")
    
    _download_file(type="planets")
    os.system("gunzip -f planets.txt.gz")

def update_database():
    

    file = open("players.txt")
    for line in file.readlines():
        if line[0] != '#':

            data_player = line.rstrip().split(" ")
            player,created = Player.objects.get_or_create(nickname=data_player[0])
            player.influence_score = int(data_player[3])
            player.hyp_rank = HYPERIUMS_RANK[int(data_player[4])]
            if int(data_player[6]) == 0:
                player.idr_score = None
            elif int(data_player[6]) > 0:
                player.idr_score = int(data_player[6])
            player.save()
    file.close()
    
    file = open("alliances.txt")
    iline = 1
    for line in file.readlines():
        if line[0] != '#':
            try :
                if iline == 1 :
                    name = " ".join(line.split(" ")[1:])
                    tag = line.split(" ")[0]
                    ally, created = Ally.objects.get_or_create(alliance_tag=tag, defaults={'name':name})
                elif iline == 4 :
                    #print ally.alliance_tag
                    data_ally = line.split(" ")
                    if len(data_ally) == 5 :
                        ally.nb_planets = int(data_ally[3])
                    elif len(data_ally) == 4 :
                        ally.nb_planets = int(data_ally[2])
                    else :
                        ally.nb_planets = 0
                    try :
                        president = Player.objects.get(nickname=data_ally[0])
                    except ObjectDoesNotExist:
                        president = None
                    ally.president = president
                    ally.save()
                    iline=0
                iline += 1
            except :
                iline = 1
                pass

    file = open("planetlist.txt")
    for line in file.readlines():
        if line[0] != '#':
            data_planet = line.rstrip().split(" ")
            planet, created = Planet.objects.get_or_create(hyperiums_id=int(data_planet[0]),
                                                           defaults= {'name':data_planet[1],
                                                                     'gouv_system':int(data_planet[2]),
                                                                     'race':int(data_planet[5]),
                                                                     'prod_type':int(data_planet[6]),
                                                                     'sc':int(data_planet[11]),
                                                                     'x':int(data_planet[3]),
                                                                     'y':int(data_planet[4]),
                                                                     'activity':int(data_planet[7])
                                                                                                      })
#             created = False
#             planet = Planet(
#                             hyperiums_id=int(data_planet[0]),
#                             name=data_planet[1],
#                             gouv_system=int(data_planet[2]),
#                             race=int(data_planet[5]),
#                             prod_type=int(data_planet[6]),
#                             x=int(data_planet[3]),
#                             y=int(data_planet[4]),
#                             activity=int(data_planet[7]),
#                             sc=int(data_planet[11])
#                             )
#             planet.save()
#             created = True
            if created == False:
                if data_planet[1] != planet.name:
                    planet.previous_name = planet.name
                    planet.name = data_planet[1]
                planet.sc = int(data_planet[11])
                planet.x = int(data_planet[3])
                planet.y = int(data_planet[4])
                planet.gouv_system = int(data_planet[2])
                planet.activity = int(data_planet[7])
            match = re.search('\[(.+)\]',data_planet[8])
            if match :
                tag = match.group(1)
                if tag and tag != '':
                    planet.ally = Ally.objects.get_or_create(alliance_tag=tag,defaults={'name':tag})[0]
            planet.save()

    for planet in Planet.objects.all() :
        planetinfo = PlanetInfo.objects.get_or_create(planet=planet)[0]

